﻿//
// MetadataResolver.cs
//
// Author:
//   Jb Evain (jbevain@gmail.com)
//
// (C) 2008 Jb Evain (http://evain.net)
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;

namespace Mono.Cecil {

	public interface IAssemblyResolver {
		AssemblyDefinition Resolve (AssemblyNameReference name);
		AssemblyDefinition Resolve (string fullname);

		//bool TryResolve (AssemblyNameReference name, out AssemblyDefinition assembly);
		//bool TryResolve (string fullname, out AssemblyDefinition assembly);

		//event AssemblyResolutionEventHandler ResolutionFailed;
	}
	/*
	public delegate void AssemblyResolutionEventHandler (object sender, AssemblyResolutionEventArgs args);

	public class AssemblyResolutionEventArgs : EventArgs {

		AssemblyNameReference assembly_name;

		public AssemblyNameReference AssemblyName {
			get { return assembly_name; }
		}

		internal AssemblyResolutionEventArgs (AssemblyNameReference name)
		{
			this.assembly_name = name;
		}
	}*/

	static class MetadataResolver {

		public static TypeDefinition Resolve (IAssemblyResolver resolver, TypeReference type)
		{
			type = type.GetElementType ();

			AssemblyNameReference reference = type.Scope as AssemblyNameReference;
			if (reference != null) {
				AssemblyDefinition assembly = resolver.Resolve (reference);
				if (assembly == null)
					return null;

				return GetType (assembly.MainModule, type);
			}

			ModuleDefinition module = type.Scope as ModuleDefinition;
			if (module != null)
				return GetType (module, type);

			ModuleReference mod_reference = type.Scope as ModuleReference;
			if (mod_reference != null) {
				foreach (ModuleDefinition netmodule in type.Module.Assembly.Modules)
					if (netmodule.Name == mod_reference.Name)
						return GetType (netmodule, type);
			}

			throw new NotImplementedException ();
		}

		static TypeDefinition GetType (ModuleDefinition module, TypeReference type)
		{
			if (!type.IsNested)
				return module.Types [type.FullName];

			var declaring_type = type.DeclaringType.Resolve ();

			if (!declaring_type.HasNestedTypes)
				return null;

			var nested_types = declaring_type.NestedTypes;

			for (int i = 0; i < nested_types.Count; i++) {
				var nested_type = nested_types [i];
				if (nested_type.Name == type.Name)
					return nested_type;
			}

			return null;
		}

		public static FieldDefinition Resolve (IAssemblyResolver resolver, FieldReference field)
		{
			TypeDefinition type = Resolve (resolver, field.DeclaringType);
			if (type == null)
				return null;

			if (!type.HasFields)
				return null;

			return GetField (type.Fields, field);
		}

		static FieldDefinition GetField (IList<FieldDefinition> fields, FieldReference reference)
		{
			for (int i = 0; i < fields.Count; i++) {
				var field = fields [i];

				if (field.Name != reference.Name)
					continue;

				if (!AreSame (field.FieldType, reference.FieldType))
					continue;

				return field;
			}

			return null;
		}

		public static MethodDefinition Resolve (IAssemblyResolver resolver, MethodReference method)
		{
			TypeDefinition type = Resolve (resolver, method.DeclaringType);
			if (type == null)
				return null;

			method = method.GetElementMethod ();

			if (!type.HasMethods)
				return null;

			return GetMethod (resolver, type, method);
		}

		static MethodDefinition GetMethod (IAssemblyResolver resolver, TypeDefinition type, MethodReference reference)
		{
			while (type != null) {
				MethodDefinition method = GetMethod (type.Methods, reference);
				if (method == null) {
					if (type.BaseType == null)
						return null;

					type = Resolve (resolver, type.BaseType);
				} else
					return method;
			}

			return null;
		}

		static MethodDefinition GetMethod (IList<MethodDefinition> methods, MethodReference reference)
		{
			for (int i = 0; i < methods.Count; i++) {
				var method = methods [i];

				if (method.Name != reference.Name)
					continue;

				if (!AreSame (method.ReturnType, reference.ReturnType))
					continue;

				if (method.HasParameters != reference.HasParameters)
					continue;

				if (!method.HasParameters && !reference.HasParameters)
					return method; //both have no parameters hence meth is the good one

				if (!AreSame (method.Parameters, reference.Parameters))
					continue;

				return method;
			}

			return null;
		}

		static bool AreSame (ParameterDefinitionCollection a, ParameterDefinitionCollection b)
		{
			var count = a.Count;

			if (count != b.Count)
				return false;

			if (count == 0)
				return true;

			for (int i = 0; i < count; i++)
				if (!AreSame (a [i].ParameterType, b [i].ParameterType))
					return false;

			return true;
		}

		static bool AreSame (TypeSpecification a, TypeSpecification b)
		{
			if (!AreSame (a.ElementType, b.ElementType))
				return false;

			if (a.IsGenericInstance)
				return AreSame ((GenericInstanceType) a, (GenericInstanceType) b);

			if (a.IsRequiredModifier || a.IsOptionalModifier)
				return AreSame ((IModifierType) a, (IModifierType) b);

			if (a.IsArray)
				return AreSame ((ArrayType) a, (ArrayType) b);

			return true;
		}

		static bool AreSame (ArrayType a, ArrayType b)
		{
			if (a.Rank != b.Rank)
				return false;

			// TODO: dimensions

			return true;
		}

		static bool AreSame (IModifierType a, IModifierType b)
		{
			return AreSame (a.ModifierType, b.ModifierType);
		}

		static bool AreSame (GenericInstanceType a, GenericInstanceType b)
		{
			if (a.GenericArguments.Count != b.GenericArguments.Count)
				return false;

			if (a.GenericArguments.Count == 0)
				return true;

			for (int i = 0; i < a.GenericArguments.Count; i++)
				if (!AreSame (a.GenericArguments [i], b.GenericArguments [i]))
					return false;

			return true;
		}

		static bool AreSame (GenericParameter a, GenericParameter b)
		{
			return a.Position == b.Position;
		}

		static bool AreSame (TypeReference a, TypeReference b)
		{
			if (a.etype != b.etype)
				return false;

			if (a is TypeSpecification)
				return AreSame ((TypeSpecification) a, (TypeSpecification) b);

			if (a is GenericParameter)
				return AreSame ((GenericParameter) a, (GenericParameter) b);

			return a.FullName == b.FullName;
		}
	}
}
